<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入员工姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工号" prop="employeeNumber">
        <el-input
          v-model="queryParams.employeeNumber"
          placeholder="请输入员工工号，唯一"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="入职日期" prop="hireDate">
        <el-date-picker clearable
          v-model="queryParams.hireDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择入职日期">
        </el-date-picker>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <!-- 添加查看详情按钮 -->
        <el-button type="info" icon="View" @click="handleViewDetails">查看详情</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['zdtj:zdtj:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['zdtj:zdtj:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['zdtj:zdtj:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['zdtj:zdtj:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-dialog v-model="showChartDialog" title="统计详情" width="60%" @opened="onDialogOpened">
    <!-- 添加日期选择器 -->
    <el-form-item label="选择月份">
      <el-date-picker
        v-model="selectedMonth"
        type="month"
        value-format="YYYY-MM"
        placeholder="请选择月份"
        @change="handleMonthChange"
      />
    </el-form-item>
    <div ref="chartRef" style="width: 100%; height: 400px;"></div>
  </el-dialog>

    <el-table v-loading="loading" :data="zdtjList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="员工ID，主键" align="center" prop="id" />
      <el-table-column label="员工姓名" align="center" prop="name" />
      <el-table-column label="员工工号" align="center" prop="employeeNumber" />
      <el-table-column label="职位" align="center" prop="departmentId">
        <template #default="scope">
          <dict-tag :options="bu_men" :value="scope.row.departmentId"/>
        </template>
      </el-table-column>
      <el-table-column label="个人缴纳" align="center" prop="personalPayment" />
      <el-table-column label="职位" align="center" prop="positionName">
       
      </el-table-column>
      <el-table-column label="公司缴纳" align="center" prop="companyPayment" />
      <el-table-column label="合计金额" align="center" prop="totalPayment" />
      <el-table-column label="入职日期" align="center" prop="hireDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.hireDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参保日期" align="center" prop="paymentMonth" />
      <el-table-column label="性别：男/女/其他" align="center" prop="gender">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.gender"/>
        </template>
      </el-table-column>
       <el-table-column label="状态" align="center" prop="type"> <!-- 修改 prop 属性为 type -->
      <template #default="scope">
        <!-- 将 value 绑定改为 scope.row.type -->
        <dict-tag :options="employee_type" :value="scope.row.type"/> 
      </template>
    </el-table-column>
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['zdtj:zdtj:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['zdtj:zdtj:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改账单统计对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="zdtjRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Zdtj">
import { listZdtj, getZdtj, delZdtj, addZdtj, updateZdtj ,getSums} from "@/api/zdtj/zdtj"
import * as echarts from 'echarts'
const { proxy } = getCurrentInstance()
const { bu_men, employee_status, employee_type ,sys_user_sex} = proxy.useDict('bu_men', 'employee_status', 'employee_type', 'sys_user_sex')

const zdtjList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const chartData = ref([])

const chartInstance = ref(null) // 使用ref管理图表实例
const showChartDialog = ref(false)
const chartRef = ref(null)

const selectedMonth = ref('')
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    employeeNumber: null,
    type: null,
    hireDate: null,
    gender: null,
    status: null,
  },
  rules: {
    name: [
      { required: true, message: "员工姓名不能为空", trigger: "blur" }
    ],
    employeeNumber: [
      { required: true, message: "员工工号，唯一不能为空", trigger: "blur" }
    ],
    gender: [
      { required: true, message: "性别：男/女/其他不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询账单统计列表 */
function getList() {
  loading.value = true
  listZdtj(queryParams.value).then(response => {
    zdtjList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

/** 查看详情按钮操作 */
async function handleViewDetails() {
  try {
    loading.value = true
    // 初始加载时清空月份选择，或者设置为当前月份
    selectedMonth.value = '' // 或者 formatDate(new Date(), 'YYYY-MM')
    const response = await getSums({ 
      paymentMonth: selectedMonth.value // 初始为空表示获取全部数据
    })
    // 调用接口获取数据（不带月份参数）

    
    if (!response || !response.data) {
      throw new Error('未获取到有效数据')
    }
    
    chartData.value = [
      { name: '个人缴纳', value: response.data.personalPayment || 0 },
      { name: '公司缴纳', value: response.data.companyPayment || 0 },
      { name: '合计金额', value: response.data.totalPayment || 0 }
    ]
    
    showChartDialog.value = true
  } catch (error) {
    console.error('加载图表数据失败:', error)
    proxy.$modal.msgError('加载统计图表失败: ' + error.message)
    showChartDialog.value = false
  } finally {
    loading.value = false
  }
}

/** 月份变化时重新获取数据 */
async function handleMonthChange() {
  if (!showChartDialog.value) return
  
  try {
    loading.value = true
    
    // 调用接口，传入选择的月份
    const response = await getSums({ 
      paymentMonth: selectedMonth.value 
    })
    
    if (!response || !response.data) {
      throw new Error('未获取到有效数据')
    }
    
    // 更新图表数据
    chartData.value = [
      { name: '个人缴纳', value: response.data.personalPayment || 0 },
      { name: '公司缴纳', value: response.data.companyPayment || 0 },
      { name: '合计金额', value: response.data.totalPayment || 0 }
    ]
    
    // 重新绘制图表
    drawChart(chartData.value)
  } catch (error) {
    console.error('加载图表数据失败:', error)
    proxy.$modal.msgError('加载统计图表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

/** 弹窗打开时绘制图表 */
function onDialogOpened() {
  nextTick(() => {
    if (chartData.value && chartData.value.length > 0) {
      drawChart(chartData.value)
    } else {
      proxy.$modal.msgWarning('没有可用的图表数据')
      showChartDialog.value = false
    }
  })
}

/** 绘制圆形统计图 */
function drawChart(data) {
  if (!chartRef.value) {
    console.error('图表容器未找到')
    return
  }
  
  try {
    // 销毁现有实例
    if (chartInstance.value) {
      chartInstance.value.dispose()
      chartInstance.value = null
    }
    
    // 初始化新实例
    chartInstance.value = echarts.init(chartRef.value)
    
    const option = {
      title: {
        text: selectedMonth.value 
          ? `${selectedMonth.value} 社保缴纳统计` 
          : '全部社保缴纳统计',
        subtext: '单位：元',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}元 ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: data.map(item => item.name)
      },
      series: [{
        name: '缴纳金额',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}元 ({d}%)'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: data
      }]
    }
    
    chartInstance.value.setOption(option)
    
    // 响应式调整大小
    const resizeHandler = () => {
      chartInstance.value && chartInstance.value.resize()
    }
    window.addEventListener('resize', resizeHandler)
    
    // 在组件卸载时移除监听器
    onUnmounted(() => {
      window.removeEventListener('resize', resizeHandler)
      if (chartInstance.value) {
        chartInstance.value.dispose()
      }
    })
  } catch (error) {
    console.error('绘制图表失败:', error)
    proxy.$modal.msgError('渲染图表时出错: ' + error.message)
  }
}
    
  



// 表单重置
function reset() {
  form.value = {
    id: null,
    avatar: null,
    name: null,
    employeeNumber: null,
    departmentId: null,
    personalPayment: null,
    positionName: null,
    type: null,
    companyPayment: null,
    totalPayment: null,
    hireDate: null,
    certificateId: null,
    paymentMonth: null,
    gender: null,
    status: null,
    insurancePlanId: null,
    delFlag: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("zdtjRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
   if (!Array.isArray(selection)) {
    selection = []
  }
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加账单统计"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getZdtj(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改账单统计"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["zdtjRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateZdtj(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addZdtj(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除账单统计编号为"' + _ids + '"的数据项？').then(function() {
    return delZdtj(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('zdtj/zdtj/export', {
    ...queryParams.value
  }, `zdtj_${new Date().getTime()}.xlsx`)
}

getList()
</script>
